using System;
using System.Linq;
using Microsoft.Collections.ObjectModel;
using Microsoft.ComponentModel;

namespace Microsoft.Windows.UserControls.ViewModels
{
    public sealed class LoggerViewItemViewModel : BindableBase, ILoggerViewItemViewModel
    {
        String header;

        LoggerViewItem.StatusType status;

        public String Header
        {
            get
            {
                return header;
            }
            set
            {
                SetProperty(ref header, value);
            }
        }

        public LoggerViewItem.StatusType Status
        {
            get
            {
                return status;
            }
            set
            {
                ((ILoggerViewItemViewModel)this).SetStatus(value, true, true);
            }
        }

        public ObservableCollectionEx<ILoggerViewItemViewModel> Children { get; private set; }

        public LoggerViewItemViewModel()
        {
            Children = new ObservableCollectionEx<ILoggerViewItemViewModel>(); 
            Children.CollectionItemChanged += OnCollectionItemChanged ;
        }

        void OnCollectionItemChanged(object sender, Collections.Specialized.NotifyCollectionItemChangedEventArgs args)
        {
            if (args.PropertyName == "Status")
                ((ILoggerViewItemViewModel)this).UpdateParentStatus();
        }

        void ILoggerViewItemViewModel.SetStatus(LoggerViewItem.StatusType status, Boolean updateChildren, Boolean updateParent)
        {
            if (this.status == status)
                return;

            this.status = status;
            if (updateChildren && this.status != LoggerViewItem.StatusType.Mixed)
                foreach (var item in Children)
                    item.SetStatus(status, true, false); 
            
            ((INotifyObject)this).OnPropertyChanged(() => Status);
        }

        void ILoggerViewItemViewModel.UpdateParentStatus()
        {
            var status = LoggerViewItem.StatusType.Mixed;
            if (Children.Where(t => t.Status == LoggerViewItem.StatusType.None).Count() == Children.Count)
                status = LoggerViewItem.StatusType.None;
            else if (Children.Where(t => t.Status == LoggerViewItem.StatusType.Checked).Count() == Children.Count)
                status = LoggerViewItem.StatusType.Checked;
            ((ILoggerViewItemViewModel)this).SetStatus(status, false, true);
        }
    }
}